<template>
  <el-form ref="forgotPasswordForm" :model="forgotPasswordFormData" autoComplete="on"
           class="card-box" label-position="left" label-width="0px">
    <el-form-item prop="email" style="border: 1px solid #ccc; padding: 0 10px; border-radius: 5px">
      <i class="iconfont">&#xe618;</i>
      <el-input v-model="forgotPasswordFormData.email" autoComplete="on" name="email" placeholder="请输入邮箱"
                type="text"/>
    </el-form-item>
    <el-form-item prop="code" style="border: 1px solid #ccc; padding-left:10px; border-radius: 5px">
      <i class="iconfont">&#xe658;</i>
      <el-input @keyup.enter.native="handleForgotPassword" v-model="forgotPasswordFormData.code" placeholder="请输入验证码">
      </el-input>
      <el-button type="primary" style="height:100%" :disabled="codeTextDisabled" @click="sendCode">{{ codeText }}</el-button>
    </el-form-item>
    <div class="login-form-footer">
      <el-link
        type="primary"
        :underline="false"
        @click="changeLoginType('login')"
      >
        返回登录
      </el-link>
    </div>
    <el-form-item>
      <el-button style="width: 100%; height: 44px" type="primary" @click="handleForgotPassword">
        提交
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {defineEmits, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {sendCodeFunc} from "@/api/login";

const emits = defineEmits(['changeLoginType'])

const forgotPasswordFormData = reactive({
  email: '',
  code:""
})
const codeText = ref('发送验证码')
const codeTextDisabled = ref(false)

const sendCode = () => {
  const emailTest = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!emailTest.test(forgotPasswordFormData.email)) {
    ElMessage.error('请输入正确的邮箱号')
    return
  }
  sendCodeFunc({ email: forgotPasswordFormData.email }).then(response => {
    if (response) {
      ElMessage.success('验证码发送成功')
      codeTextDisabled.value = true
      let time = 60
      const timer = setInterval(() => {
        time--
        codeText.value = `${time}秒后重新发送`
        if (time <= 0) {
          clearInterval(timer)
          codeText.value = '发送验证码'
          codeTextDisabled.value = false
        }
      }, 1000)
    }
  })
}

const handleForgotPassword = () => {
  ElMessage.success("已发送重置密码邮件，请查收")
}
const changeLoginType = (type: "login" | "register" | "forgotPassword") => {
  emits('changeLoginType', type)
}
</script>

<style lang="scss" scoped>
.el-form {
  .login-form-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 10px 0 20px;
  }
  .el-input {
    height: 47px;
    flex: 1;

    :deep().el-input__wrapper {
      background-color: transparent;
      box-shadow: none;
    }

    :deep()input {
      border: 0;
      -webkit-appearance: none;
      border-radius: 0;
      padding: 12px 5px 12px 15px;
      height: 100%;
      font-size: 16px;
    }
  }
}

.iconfont {
  font-size: 30px;
}
</style>
